package com.pandora.credit.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.pandora.common.util.*;
import com.pandora.credit.dao.AppUpgradeDao;
import com.pandora.credit.dto.request.UpgradeRequest;
import com.pandora.credit.dto.response.GetCaptchaResponse;
import com.pandora.credit.dto.response.UpgradeInfoResponse;
import com.pandora.credit.entity.AppUpgrade;
import com.pandora.credit.exception.ParameterErrorException;
import com.pandora.credit.exception.sms.CaptchaCodeErrorException;
import com.pandora.credit.service.AppUpgradeService;
import org.patchca.service.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;

/**
 * @author developer
 */
@Service
public class AppUpgradeServiceImpl implements AppUpgradeService {

    @Autowired
    private AppUpgradeDao appUpgradeDao;

    @Override
    public AppUpgrade getByPvvb(String platform, String osVersion, String model, String brand) {
        List<AppUpgrade> li = appUpgradeDao.queryByPvvb(platform, osVersion, model, brand);
        if (li != null && li.size() > 0) {
            AppUpgrade appUpgrade = li.get(0);
            return appUpgrade;
        }
        return null;
    }

    @Override
    public UpgradeInfoResponse getUpgradeInfo(UpgradeRequest req) {
        String platform = req.getPlatform();
        String version = req.getVersion();
        String model = req.getModel();
        String brand = req.getBrand();
        if (VerifyUtil.isEmpty(platform) || VerifyUtil.isEmpty(version)) {
            throw new ParameterErrorException();
        }
        AppUpgrade appUpgrade = getByPvvb(platform, version, model, brand);
        if (appUpgrade == null) {
            appUpgrade = getByPvvb(null, version, model, brand);
            if (appUpgrade == null) {
                appUpgrade = getByPvvb(null, null, model, brand);
                if (appUpgrade == null) {
                    appUpgrade = getByPvvb(null, null, null, brand);
                }
            }
        }
        int force = Constants.UPGRADE_NO;
        String messages = "";
        String currentU = "";
        String urlU = "";
        if (appUpgrade != null) {
            String forceUpgradeU = appUpgrade.getForceUpgradeVersions();
            String upgradeU = appUpgrade.getUpgradeVersion();
            currentU = appUpgrade.getCurrentVersion();
            urlU = appUpgrade.getDownloadUrl();
            String messageU = appUpgrade.getMessage();

            if(vInForce(version, forceUpgradeU, upgradeU)){
                force = Constants.UPGRADE_FORCE;
            }
            else if(vUnderUpgrade(version, upgradeU)){
                force = Constants.UPGRADE_RECOMMEND;
            }

            if (VerifyUtil.isEmpty(messageU)) {
                messages = null;
            } else {
                JSONObject jo = JSONObject.parseObject(messageU);
                String forceMessage = jo.getString("force");
                String normalMessage = jo.getString("normal");
                if (force == Constants.UPGRADE_FORCE) {
                    messages = forceMessage;
                } else if (force == Constants.UPGRADE_RECOMMEND) {
                    messages = normalMessage;
                } else {
                    messages = null;
                }
            }
        }
        UpgradeInfoResponse upgradeInfoResponse = new UpgradeInfoResponse();
        upgradeInfoResponse.setForce(force);
        upgradeInfoResponse.setMessage(messages);
        upgradeInfoResponse.setVersion(currentU);
        upgradeInfoResponse.setUrl(urlU);
        return upgradeInfoResponse;
    }

    @Override
    public GetCaptchaResponse doGetCaptcha(String accessToken) {
        Captcha captcha = CaptchaUtil.getCaptchaService().getCaptcha();
        String s = captcha.getChallenge();
        BufferedImage bufferedImage = captcha.getImage();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "jpeg", stream);
            byte[] bytes = stream.toByteArray();
            String jpegBase64 = Encodes.encodeBase64(bytes);
            jpegBase64 = jpegBase64.replaceAll("\n", "").replaceAll("\r", "");
            System.out.println(s);
            System.out.println(jpegBase64);

            JedisUtil.set(Constants.BUSINESS_REDIS_URL,
                    StringUtils.getStrParam(Constants.MOBILE_CAPTCHA_KEY, accessToken), s,
                    Constants.SMS_EXPIRATION_TIME);
            return new GetCaptchaResponse(jpegBase64);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CaptchaCodeErrorException();
        }
    }

    private boolean vInForce(String v, String forceV, String upgradeV){
        String[] forceArray = forceV.split(MagicConst.SPLIT_COMMA_HALF_WIDTH);
        List<String> forceList = new LinkedList<>();
        List<Boolean> forceBoolList = new LinkedList<>();
        forceList.addAll(Arrays.asList(forceArray));
        for(String x : forceArray){
            forceBoolList.add(versionInRange(v, x, forceList));
        }
        boolean re = false;
        for(boolean b : forceBoolList){
            if(b){
                re = true;
                break;
            }
        }
        return re;
    }

    private boolean versionInRange(String v, String z, List<String> forceList){
        if(!z.contains(MagicConst.SPLIT_SEP)){
            return v.equals(z);
        }
        else {
            String[] s = z.split(MagicConst.SPLIT_SEP);
            if(s.length == MagicConst.NUM_2){
                return s[0].compareTo(v)<=0 && s[1].compareTo(v)>=0;
            }
        }
        return false;
    }

    private boolean vUnderUpgrade(String version, String upgradeV){
        return version.compareTo(upgradeV) <= 0;
    }
}
